package com.lhczf.lucenedb.consumer;

import com.lhczf.lucenedb.production.AbstractDataQueues;
import com.lhczf.lucenedb.service.LuceneDbServer;
import com.lhczf.lucenedb.service.ZipServer;
import com.lhczf.lucenedb.util.BeanUtil;
import com.lhczf.lucenedb.util.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 刘华春
 * @date: 2019/2/6
 */
@Slf4j
public class BackUpDataConsumer extends AbstractDataQueues implements Runnable {

    @Override
    protected void dataQueueConfig() {
        //这里不做任何事情
    }

    @Override
    public void run() {
        log.info("备份线程已经启动。");
        BACKUP_INDEX_DATA_MAP.forEach((indexName, daysMap) -> {
            List<String> removeName = new ArrayList<>();
            daysMap.forEach((dayName, dataDirLit) -> {
                if (!dataDirLit.isEmpty()) {
                    backupEveryDayData(indexName, removeName, dayName, dataDirLit);
                }
            });
            for (String dayName : removeName) {
                String dataSubDir = daysMap.get(dayName).get(0);
                String rootDir = dataSubDir.substring(0, dataSubDir.lastIndexOf(File.separator));
                File file = new File(rootDir);
                FileUtil.safeDeleteFile(file);

                daysMap.remove(dayName);
            }
        });
    }

    private void backupEveryDayData(String indexName, List<String> removeName, String dayName, List<String> dataDirLit) {
        ZipServer zipServer = BeanUtil.getInstance().getBean(ZipServer.class);
        LuceneDbServer server = BeanUtil.getInstance().getBean(LuceneDbServer.class);

        String indexDir = dataDirLit.get(0);
        String rootDir = indexDir.substring(0, indexDir.lastIndexOf(File.separator));
        int threadNum = server.getEveryIndexDealThreadNum().get(indexName);
        if (dataDirLit.size() == threadNum) {
            boolean success = backDataBegin(zipServer, indexName, dayName, rootDir);
            if (success) {
                removeName.add(dayName);
            }
        }
    }

    private boolean backDataBegin(ZipServer zipServer, String indexName, String dayName, String indexDir) {
        log.info("备份【{}】索引【{}】日的数据开始。", indexName, dayName);
        LocalDateTime start = LocalDateTime.now();
        boolean success = zipServer.initZipInfoAndZip(indexDir);
        LocalDateTime end = LocalDateTime.now();
        Duration duration = Duration.between(start, end);
        log.info("备份【{}】索引【{}】日的数据结束，耗时共【{}】毫秒", indexName, dayName, duration.toMillis());
        return success;
    }
}
